import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzDatePickerModule } from 'ng-zorro-antd/date-picker';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { NzDividerModule } from 'ng-zorro-antd/divider';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzMessageModule } from 'ng-zorro-antd/message';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-allocation',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    FormsModule,
    NzTableModule,
    NzButtonModule,
    NzInputModule,
    NzSelectModule,
    NzDatePickerModule,
    NzIconModule,
    NzDividerModule,
    NzMessageModule,
    NzTagModule
  ],
  templateUrl: './allocation.component.html',
  styleUrls: ['./allocation.component.scss']
})
export class AllocationComponent implements OnInit {
  listOfData: any[] = [];
  loading = false;
  
  // 分页相关
  currentPage = 1;
  pageSize = 10;
  totalPages = 1;
  pageNumbers: number[] = [1];
  
  // 搜索条件
  searchParams = {
    allocationNo: '',
    status: null,
    outWarehouseStatus: null,
    inWarehouseStatus: null,
    allocationDate: null
  };

  // 表格滚动相关
  isScrolled = false;
  
  // 选中行
  selectedRows: any[] = [];

  // 单据状态选项
  statusOptions = [
    { value: '', label: '全部' },
    { value: '草稿', label: '草稿' },
    { value: '待审核', label: '待审核' },
    { value: '驳回', label: '驳回' },
    { value: '通过', label: '通过' },
    { value: '已完成', label: '已完成' }
  ];

  // 出入库状态选项
  warehouseStatusOptions = [
    { value: '', label: '全部' },
    { value: '未出库', label: '未出库' },
    { value: '部分出库', label: '部分出库' },
    { value: '已出库', label: '已出库' },
    { value: '未入库', label: '未入库' },
    { value: '部分入库', label: '部分入库' },
    { value: '已入库', label: '已入库' }
  ];

  constructor(
    private message: NzMessageService,
    private router: Router,
    private http: HttpClient
  ) {}

  ngOnInit(): void {
    this.loadData();
  }

  loadData(): void {
    this.loading = true;
    
    // 使用真实API请求替代模拟数据
    this.http.get<any>('https://localhost:44350/api/app/allocation/ocation-list')
      .subscribe({
        next: (res) => {
          console.log("调拨单列表",res);
          this.listOfData = res.items || [];
          this.updatePagination();
          this.loading = false;
        },
        error: (err) => {
          this.message.error('获取调拨单列表失败');
          this.loading = false;
        }
      });
  }
  
  // 更新分页信息
  updatePagination(): void {
    this.totalPages = Math.ceil(this.listOfData.length / this.pageSize) || 1;
    this.pageNumbers = this.generatePageNumbers();
  }
  
  // 生成页码数组
  generatePageNumbers(): number[] {
    const pages: number[] = [];
    for (let i = 1; i <= this.totalPages; i++) {
      pages.push(i);
    }
    return pages;
  }
  
  // 切换页码
  changePage(page: number): void {
    this.currentPage = page;
  }

  // 获取单据状态颜色
  getStatusColor(status: string): string {
    switch (status) {
      case '草稿':
        return 'blue';
      case '待审核':
        return 'orange';
      case '驳回':
        return 'red';
      case '通过':
        return 'green';
      case '已完成':
        return 'green';
      default:
        return 'default';
    }
  }

  // 获取状态徽章样式类
  getStatusBadgeClass(status: string): string {
    switch (status) {
      case '草稿':
        return 'bg-primary';
      case '待审核':
        return 'bg-warning';
      case '驳回':
        return 'bg-danger';
      case '通过':
        return 'bg-success';
      case '已完成':
        return 'bg-success';
      default:
        return 'bg-secondary';
    }
  }

  // 获取仓库状态颜色
  getWarehouseStatusColor(status: string): string {
    switch (status) {
      case '未出库':
      case '未入库':
        return 'blue';
      case '部分出库':
      case '部分入库':
        return 'orange';
      case '已出库':
      case '已入库':
        return 'green';
      default:
        return 'default';
    }
  }

  // 获取仓库状态徽章样式类
  getWarehouseStatusBadgeClass(status: string): string {
    switch (status) {
      case '未出库':
      case '未入库':
        return 'bg-primary';
      case '部分出库':
      case '部分入库':
        return 'bg-warning';
      case '已出库':
      case '已入库':
        return 'bg-success';
      default:
        return 'bg-secondary';
    }
  }

  search(): void {
    this.loadData();
    this.message.success('查询成功');
  }

  reset(): void {
    this.searchParams = {
      allocationNo: '',
      status: null,
      outWarehouseStatus: null,
      inWarehouseStatus: null,
      allocationDate: null
    };
    this.loadData();
  }

  add(): void {
    // 跳转到新增页面
    this.router.navigate(['/allocation/add']);
  }

  edit(id: number): void {
    // 确保id有效
    if (!id) {
      this.message.error('无效的调拨单ID');
      return;
    }
    
    // 显示加载状态
    this.loading = true;
    
    // 查找当前行数据
    const currentRowData = this.listOfData.find(item => item.id === id);
    
    if (currentRowData) {
      // 直接将当前行数据存储到localStorage
      localStorage.setItem('editAllocationData', JSON.stringify(currentRowData));
      
      // 跳转到编辑页面
      const url = `/inventory/allocation/edit/${id}`;
      this.router.navigateByUrl(url);
      
      this.loading = false;
    } else {
      // 如果在列表中找不到对应数据，则从API获取
      this.http.get<any>(`https://localhost:44350/api/app/allocation/${id}`)
        .subscribe({
          next: (response) => {
            // 将数据存储到localStorage
            localStorage.setItem('editAllocationData', JSON.stringify(response));
            
            // 跳转到编辑页面
            const url = `/inventory/allocation/edit/${id}`;
            this.router.navigateByUrl(url);
          },
          error: (error) => {
            this.message.error('获取调拨单数据失败: ' + (error.error?.message || '未知错误'));
            this.loading = false;
          }
        });
    }
  }

  // 编辑调拨单
  editAllocation(id: string, currentRowData: any): void {
    if (!id) {
      this.message.error('无效的调拨单ID');
      return;
    }
    
    if (currentRowData) {
      // 直接将当前行数据存储到localStorage
      localStorage.setItem('editAllocationData', JSON.stringify(currentRowData));
      this.router.navigate(['/inventory/allocation/edit', id]);
      return;
    }
    
    // 如果没有当前行数据，从API获取
    this.http.get<any>(`https://localhost:44350/api/app/allocation/${id}`)
      .subscribe({
        next: (response) => {
          console.log('编辑前获取到调拨单数据:', response);
          
          // 将数据存储到localStorage
          localStorage.setItem('editAllocationData', JSON.stringify(response));
          
          // 跳转到编辑页面
          this.router.navigate(['/inventory/allocation/edit', id]);
        },
        error: (error) => {
          this.message.error('获取调拨单数据失败: ' + (error.error?.message || '未知错误'));
        }
      });
  }

  // 查看详情
  viewDetail(id: number): void {
    if (!id) {
      this.message.error('无效的调拨单ID');
      return;
    }
    
    // 查找当前行数据
    const currentRowData = this.listOfData.find(item => item.id === id);
    
    if (currentRowData) {
      // 存储当前行数据到localStorage，用于详情页显示
      localStorage.setItem('allocationDetailData', JSON.stringify(currentRowData));
      // 同时也存储到editAllocationData，这样从详情页点击编辑按钮时也能加载数据
      localStorage.setItem('editAllocationData', JSON.stringify(currentRowData));
      console.log('存储调拨单详情数据到localStorage:', currentRowData);
      
      // 跳转到详情页面
      this.router.navigate(['/inventory/allocation/detail', id]);
    } else {
      // 如果在列表中找不到数据，直接跳转(后续由详情页从API获取)
      this.router.navigate(['/inventory/allocation/detail', id]);
    }
  }

  delete(id: number): void {
    // 删除操作
    this.message.success('删除成功');
  }

  audit(id: number): void {
    // 审核操作
    this.message.success('审核成功');
  }

  export(): void {
    // 导出操作
    this.message.success('导出成功');
  }
  
  copy(id: number): void {
    // 复制操作
    this.message.success('复制成功');
  }
  
  // 表格滚动事件处理
  onTableScroll(event: Event): void {
    const target = event.target as HTMLElement;
    this.isScrolled = target.scrollLeft > 0;
  }
  
  // 处理选中行变更
  onItemCheckedChange(item: any, checked: boolean): void {
    if (checked) {
      this.selectedRows = [...this.selectedRows, item];
    } else {
      this.selectedRows = this.selectedRows.filter(row => row.id !== item.id);
    }
  }
  
  // 全选/取消全选
  toggleSelectAll(event: Event): void {
    const checked = (event.target as HTMLInputElement).checked;
    if (checked) {
      this.selectedRows = [...this.listOfData];
    } else {
      this.selectedRows = [];
    }
  }
  
  // 检查是否所有行都被选中
  isAllSelected(): boolean {
    return this.listOfData.length > 0 && this.selectedRows.length === this.listOfData.length;
  }
  
  // 检查是否部分行被选中
  isIndeterminate(): boolean {
    return this.selectedRows.length > 0 && this.selectedRows.length < this.listOfData.length;
  }
  
  // 计算总数量
  get totalQuantity(): number {
    return this.listOfData.reduce((sum, item) => sum + (item.allocationQuantity || 0), 0);
  }
  
  // 计算总金额
  get totalAmount(): number {
    return this.listOfData.reduce((sum, item) => sum + (item.allocationAmount || 0), 0);
  }
} 